<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
.shadowbox{
	background:white;
	border-radius: 10px;
	border: outset 5px;
	box-shadow: 18px 18px 18px black;
	padding:5px;
	margin:5px;
}
.2dcanvas{
	box-shadow: 0px 0px 80px black inset;
}
	body{
	background:lightblue;
	}
      .completions {
        position: absolute;
        z-index: 10;
        overflow: hidden;
        -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
        -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
        box-shadow: 2px 3px 5px rgba(0,0,0,.2);
      }
      .completions select {
        background: #fafafa;
        outline: none;
        border: none;
        padding: 0;
        margin: 0;
        font-family: monospace;
      }
      .CodeMirror {
        border: 1px solid #eee;
        background: white;
      }
  html { height: 100% }
  body { height: 100%; margin: 0px; padding: 0px }
#container {
	background: #000;
	width: 800px;
	height: 300px;
}

</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="jquery.rotate.1-1.js"></script>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="lib/codemirror.js"></script>
<link rel="stylesheet" href="mode/javascript/javascript.css">
<script src="mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="css/docs.css">
<script src="Three.js"></script>
<script type="text/javascript">
$(function(){

	$('#toggleHistoryButton').trigger('click');
	$('#togglecanvas').trigger('click');
	(function () {
		  // Minimal event-handling wrapper.
		  function stopEvent() {
		    if (this.preventDefault) {this.preventDefault(); this.stopPropagation();}
		    else {this.returnValue = false; this.cancelBubble = true;}
		  }
		  function addStop(event) {
		    if (!event.stop) event.stop = stopEvent;
		    return event;
		  }
		  function connect(node, type, handler) {
		    function wrapHandler(event) {handler(addStop(event || window.event));}
		    if (typeof node.addEventListener == "function")
		      node.addEventListener(type, wrapHandler, false);
		    else
		      node.attachEvent("on" + type, wrapHandler);
		  }

		  function forEach(arr, f) {
		    for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
		  }

		  editor = CodeMirror.fromTextArea(document.getElementById("code"), {
		    lineNumbers: true,
		    onKeyEvent: function(i, e) {
		      // Hook into ctrl-space
		      if (e.keyCode == 32 && (e.ctrlKey || e.metaKey) && !e.altKey) {
		        e.stop();
		        return startComplete();
		      }
		    }
		  });

		  function startComplete() {
		    // We want a single cursor position.
		    if (editor.somethingSelected()) return;
		    // Find the token at the cursor
		    var cur = editor.getCursor(false), token = editor.getTokenAt(cur), tprop = token;
		    // If it's not a 'word-style' token, ignore the token.
		    if (!/^[\w$_]*$/.test(token.string)) {
		      token = tprop = {start: cur.ch, end: cur.ch, string: "", state: token.state,
		                       className: token.string == "." ? "js-property" : null};
		    }
		    // If it is a property, find out what it is a property of.
		    while (tprop.className == "js-property") {
		      tprop = editor.getTokenAt({line: cur.line, ch: tprop.start});
		      if (tprop.string != ".") return;
		      tprop = editor.getTokenAt({line: cur.line, ch: tprop.start});
		      if (!context) var context = [];
		      context.push(tprop);
		    }
		    var completions = getCompletions(token, context);
		    if (!completions.length) return;
		    function insert(str) {
		      editor.replaceRange(str, {line: cur.line, ch: token.start}, {line: cur.line, ch: token.end});
		    }
		    // When there is only one completion, use it directly.
		    if (completions.length == 1) {insert(completions[0]); return true;}

		    // Build the select widget
		    var complete = document.createElement("div");
		    complete.className = "completions";
		    var sel = complete.appendChild(document.createElement("select"));
		    sel.multiple = true;
		    for (var i = 0; i < completions.length; ++i) {
		      var opt = sel.appendChild(document.createElement("option"));
		      opt.appendChild(document.createTextNode(completions[i]));
		    }
		    sel.firstChild.selected = true;
		    sel.size = Math.min(10, completions.length);
		    var pos = editor.cursorCoords();
		    complete.style.left = pos.x + "px";
		    complete.style.top = pos.yBot + "px";
		    document.body.appendChild(complete);
		    // Hack to hide the scrollbar.
		    if (completions.length <= 10)
		      complete.style.width = (sel.clientWidth - 1) + "px";

		    var done = false;
		    function close() {
		      if (done) return;
		      done = true;
		      complete.parentNode.removeChild(complete);
		    }
		    function pick() {
		      insert(sel.options[sel.selectedIndex].value);
		      close();
		      setTimeout(function(){editor.focus();}, 50);
		    }
		    connect(sel, "blur", close);
		    connect(sel, "keydown", function(event) {
		      var code = event.keyCode;
		      // Enter and space
		      if (code == 13 || code == 32) {event.stop(); pick();}
		      // Escape
		      else if (code == 27) {event.stop(); close(); editor.focus();}
		      else if (code != 38 && code != 40) {close(); editor.focus(); setTimeout(startComplete, 50);}
		    });
		    connect(sel, "dblclick", pick);

		    sel.focus();
		    // Opera sometimes ignores focusing a freshly created node
		    if (window.opera) setTimeout(function(){if (!done) sel.focus();}, 100);
		    return true;
		  }

		  var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
		                     "toUpperCase toLowerCase split concat match replace search").split(" ");
		  var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
		                    "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
		  var funcProps = "prototype apply call bind".split(" ");
		  var keywords = ("break case catch continue debugger default delete do else false finally for function " +
		                  "if in instanceof new null return switch throw true try typeof var void while with").split(" ");

		  function getCompletions(token, context) {
		    var found = [], start = token.string;
		    function maybeAdd(str) {
		      if (str.indexOf(start) == 0) found.push(str);
		    }
		    function gatherCompletions(obj) {
		      if (typeof obj == "string") forEach(stringProps, maybeAdd);
		      else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
		      else if (obj instanceof Function) forEach(funcProps, maybeAdd);
		      for (var name in obj) maybeAdd(name);
		    }

		    if (context) {
		      // If this is a property, see if it belongs to some object we can
		      // find in the current environment.
		      var obj = context.pop(), base;
		      if (obj.className == "js-variable")
		        base = window[obj.string];
		      else if (obj.className == "js-string")
		        base = "";
		      else if (obj.className == "js-atom")
		        base = 1;
		      while (base != null && context.length)
		        base = base[context.pop().string];
		      if (base != null) gatherCompletions(base);
		    }
		    else {
		      // If not, just look in the window object and any local scope
		      // (reading into JS mode internals to get at the local variables)
		      for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
		      gatherCompletions(window);
		      forEach(keywords, maybeAdd);
		    }
		    return found;
		  }
		})();

});




function runit()
{
	if(document.getElementById('cbClearCanvas').checked==true){
		var canvas = document.getElementById("canvas");
		canvas.width = canvas.width;
	}
	var post_code=document.getElementById("post_code").value;
	var pre_code=editor.getValue();//document.getElementById("code").value;
	document.getElementById("post_code").value=post_code+"\n/*Execution Time: "+ new Date()+ "*/\n"+pre_code;

	eval(editor.getValue());
	$('#post_code').attr('scrollTop',$('#post_code').attr('scrollHeight'));
}

function toggleDiv(divId,toggleBtn){

	var btvalue= $('#'+toggleBtn).attr('value');
	if(btvalue=="-"){
		$('#'+divId).hide();
		$('#'+toggleBtn).val("+");
	}
	if(btvalue=="+"){
		$('#'+divId).show();
		$('#'+toggleBtn).val("-");
	}
}


function toggleHistory(){

	var btvalue= $('#toggleHistoryButton').attr('value');
	if(btvalue=="-"){
		$('#historyDiv').hide();
		$('#toggleHistoryButton').val("+");
	}
	if(btvalue=="+"){
		$('#historyDiv').show();
		$('#toggleHistoryButton').val("-");
	}
}

function handleKeyDown() {
	keyDown(event.keyCode);
}
</script>
<script type="text/javascript" src="glMatrix-0.9.5.min.js"></script>
<script type="text/javascript" src="webgl-utils.js"></script>

<script id="shader-fs" type="x-shader/x-fragment">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying vec4 vColor;

    void main(void) {
        gl_FragColor = vColor;
    }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
    attribute vec3 aVertexPosition;
    attribute vec4 aVertexColor;

    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;

    varying vec4 vColor;

    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
        vColor = aVertexColor;
    }
</script>



</head>
<body  >
<h1>WebGL/Canvas Sandbox</h1>


<h2><a href="http://learningwebgl.com/blog/?p=370" target="blank">webgl tutorials</a></h2>
<br/>
<input type="button" id="toggleGLcanvas" value="-" onclick="toggleDiv('container','toggleGLcanvas')" >viewport	<p>
<div id="container" class="shadowbox"></div>
<input type="button" id="togglecanvas" value="-" onclick="toggleDiv('canvas','togglecanvas')" >canvas	<p>
	<canvas id="canvas" class="shadowbox 2dcanvas" height="400px" width="800px"></canvas>
	<br/>
	<div id="inputDiv" class="inputDiv shadowbox" style="width:800px;" >
		<textarea rows="5"  id="code" style="width:800px;"  onchange="resizeDiv('inputDiv')">


	// set the scene size
	var WIDTH = 800,
	    HEIGHT = 300;

	// set some camera attributes
	var VIEW_ANGLE = 45,
	    ASPECT = WIDTH / HEIGHT,
	    NEAR = 0.1,
	    FAR = 10000;

	// get the DOM element to attach to
	// - assume we've got jQuery to hand
	var $container = $('#container');

	// create a WebGL renderer, camera
	// and a scene
	var renderer = new THREE.WebGLRenderer();
	var camera = new THREE.PerspectiveCamera(  VIEW_ANGLE,
	                                ASPECT,
	                                NEAR,
	                                FAR  );
	var scene = new THREE.Scene();

	// the camera starts at 0,0,0 so pull it back
	camera.position.z = 300;

	// start the renderer
	renderer.setSize(WIDTH, HEIGHT);

	// attach the render-supplied DOM element
	$container.append(renderer.domElement);

	// create the sphere's material
	var sphereMaterial = new THREE.MeshLambertMaterial(
	{
	    color: 0xCC0000
	});

	// set up the sphere vars
	var radius = 50, segments = 16, rings = 16;

	// create a new mesh with sphere geometry -
	// we will cover the sphereMaterial next!
	var sphere = new THREE.Mesh(
	   new THREE.SphereGeometry(radius, segments, rings),
	   sphereMaterial);

	// add the sphere to the scene
	scene.add(sphere);

	// create a point light
	var pointLight = new THREE.PointLight( 0xFFFFFF );

	// set its position
	pointLight.position.x = 10;
	pointLight.position.y = 50;
	pointLight.position.z = 130;

	// add to the scene
	scene.add(pointLight);

	// draw!
	renderer.render(scene, camera);
		</textarea>
  		 <input name="submit" type="button" value="Run()" onclick="runit()" style="align:right;">
  		 <input type="checkbox" id="cbClearCanvas" checked><label for="cbClearCanvas">Clear Canvas</label>
	</div>
<br/>
	<input type="button" id="toggleHistoryButton" value="-" onclick="toggleDiv('historyDiv','toggleHistoryButton');" >History	<p>
	<div id="historyDiv" class="historyDiv shadowbox" style="width:800px;">
		<textarea rows="5"  id="post_code" style="width:800px;"  onchange="resizeDiv('historyDiv')">

		</textarea>
	</div>

</body>
</html>
